//
//  ScanAllViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/20.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "ScanAllViewController.h"
#import "QuickScanCollectionView.h"
#import "ColelctViewController.h"
#import "LoginViewController.h"

#define KpageCount  @"5"

@interface ScanAllViewController ()
@property (weak, nonatomic) IBOutlet UIView *scanV;
@property (weak, nonatomic) IBOutlet UIView *buttonV;
@property (weak, nonatomic) IBOutlet UIButton *collectionButon;
@property (weak, nonatomic) IBOutlet UIButton *rightButton;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UILabel *paricelabel;
@property(nonatomic,strong)NSMutableArray *dataSouce;
@property(nonatomic,strong)QuickScanCollectionView *scan;
@property(nonatomic,assign)int  currentIndex;
@end

@implementation ScanAllViewController
-(instancetype)init{
    self = [super init];
    if(self){
      //监听滑动页数
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(scrollPage:) name:@"scrollPage" object:nil];
    }
    return self;
}

//快速浏览时发来的通知 包含了当前页数的信息
- (void)scrollPage:(NSNotification *)noti{
    //设置变化页数的颜色
    NSString *str = noti.object;
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:str];
     NSUInteger end = [str rangeOfString:@"/" ].location;
    NSRange redRange = NSMakeRange(0, end);
    [noteStr addAttribute:NSForegroundColorAttributeName value:DEF_COLOR range:redRange];
    [ self.titleLabel setAttributedText:noteStr] ;
    self.currentIndex =  [[noti.object substringToIndex:1] intValue]-1;
    ScanCollectionModel *model = self.dataSouce[self.currentIndex];
    self.paricelabel.text =   [NSString stringWithFormat:@"￥ %@",model.price];
    
    
    //设置收藏按钮的状态
    [self setCollectionBtnStatusWithModel:self.dataSouce[self.currentIndex]];
}
//设置收藏按钮的状态
-(void)setCollectionBtnStatusWithModel:(QickScanModel*)item{
    if(item.isCollection){
        [self.collectionButon setImage:[UIImage imageNamed:@"icon_shoucang_sel"] forState:UIControlStateNormal];
         [self.rightButton setTitle:@"取消收藏" forState:UIControlStateNormal];
    }else{
        [self.collectionButon setImage:[UIImage imageNamed:@"icon_shoucang_nor"] forState:UIControlStateNormal];
         [self.rightButton setTitle:@"加入收藏" forState:UIControlStateNormal];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    ISNOTNEEDMESSAGEBTN =NO;
    self.view.backgroundColor = [UIColor blackColor];
    self.currentPage= 1;
    QuickScanCollectionView *scan = [[QuickScanCollectionView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height-kNaviBarHeight-99)];
    scan.entryFromStore = YES;
    scan.count = 2;
    scan.isNeedLoadMore = YES;
      [self.scanV addSubview:scan];
    _scan = scan;
    [self customTitleV];
    [self customRightBarItem];
    [self.view bringSubviewToFront:self.buttonV];
    self.buttonV.backgroundColor = [UIColor blackColor];
   
    __weak typeof(self) weakSelf = self;
    scan.noPicsBlock = ^{//第一次加载没有图片的回调
        [weakSelf performSelector:@selector(noPics) withObject:nil afterDelay:1];
    };
     //更新数据源
    scan.updataDataSourceBlock = ^(NSMutableArray *dataSource){
        weakSelf.dataSouce = dataSource;
    };
    //加载更多数据
    scan.loadMoreBlock = ^{
        [weakSelf loadMoreData];
    };
    //加载数据
    if(self.paramDic){
        [self loadSortData];
    }else{
        [self loadDataWithPage:1];
    }
}

-(void)loadMoreData{
    self.currentPage++;
    if(self.paramDic){
        [self loadPageDataWithPage:self.currentPage];
    }else{
        [self loadDataWithPage:self.currentPage];
    }
}

//筛选页面进入快速浏览页面获取数据的接口
-(void)loadSortData{
    [self loadPageDataWithPage:1];
}

-(void)loadPageDataWithPage:(NSInteger)page{
    NSString *pages = [NSString stringWithFormat:@"%ld",page];
    if(page>1){
        NSMutableDictionary *pdic =self.paramDic.mutableCopy;
        [pdic setValue:pages forKey:@"currentPage"];
        self.paramDic = pdic.copy;
        
    }
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:DOSREEN paramters:self.paramDic afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"根据产品类别查询所有商品--快速浏览----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]) return ;
            NSArray *products = dataDic[@"products"];
            NSMutableArray *pics = [NSMutableArray array];
            for(NSDictionary *dic in products){
                QickScanModel *model = [[QickScanModel  alloc]init];
                model.pid = dic[@"productId"];
                model.price = [NSString stringWithFormat:@"%@",dic[@"price"]];
                model.pic = dic[@"productPic"];
                model.isCollection = [dic[@"isCollection"] boolValue];
                [pics addObject:model];
            }
            if(page>1){
                [[NSNotificationCenter defaultCenter]postNotificationName:@"ScanAllLoadMoreData" object:nil];
            }else{
                NSString *cout = [NSString stringWithFormat:@"1 / %zd",pics.count];
                NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:cout];
                NSRange redRange = NSMakeRange(0, 1);
                [noteStr addAttribute:NSForegroundColorAttributeName value:DEF_COLOR range:redRange];
                [ self.titleLabel setAttributedText:noteStr] ;
            }
            weakSelf.scan.dataArr = pics;
        }
    }];

}

////2.61 店铺内商品快速查看接口
-(void)loadDataWithPage:(NSInteger)page{

    if(!USERID.length){
        USERID= @"";
    }
    NSString *pages = [NSString stringWithFormat:@"%ld",page];
       NSDictionary *paraDic = @{
                              @"storeId":self.storeId,
                              @"page":pages,
                              @"size":KpageCount,
                              @"userId":USERID
                            };
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:QUICKVIEW paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"店铺内商品快速查看接口---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
              if([dataDic isKindOfClass:[NSNull class]]) return ;
            NSArray *products = dataDic[@"products"];
                NSMutableArray *pics = [NSMutableArray array];
                for(NSDictionary *dic in products){
                QickScanModel *model = [[QickScanModel  alloc]init];
                model.pid = dic[@"pId"];
                model.price =[NSString stringWithFormat:@"%@",dic[@"pPrice"]];
                model.pic = dic[@"pPic"];
                model.isCollection = [dic[@"isCollection"] boolValue];
                [pics addObject:model];
            }
            if(page>1){
                [[NSNotificationCenter defaultCenter]postNotificationName:@"ScanAllLoadMoreData" object:nil];
            }else{
                NSString *cout = [NSString stringWithFormat:@"1 / %zd",pics.count];
                NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:cout];
                NSRange redRange = NSMakeRange(0, 1);
                [noteStr addAttribute:NSForegroundColorAttributeName value:DEF_COLOR range:redRange];
                [ self.titleLabel setAttributedText:noteStr] ;
            }
            
            weakSelf.scan.dataArr = pics;
            }
    }];
}

-(void)noPics{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)customRightBarItem{
    //显示价格的Label
    _paricelabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 21)];
    _paricelabel.font = [UIFont systemFontOfSize:14];
    _paricelabel.textColor = [UIColor whiteColor];
    _paricelabel.textAlignment = NSTextAlignmentRight;
    _paricelabel.backgroundColor =[UIColor clearColor];
    self.rightItem = _paricelabel;
}
-(void)customTitleV{
    //显示当前页数和总页数的label
    _titleLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 21)];
//    NSString *cout = [NSString stringWithFormat:@"1 / %ld",self.dataSouce.count];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont systemFontOfSize:14];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.backgroundColor = [UIColor clearColor];
   
    _titleLabel.centerX = Main_Screen_Width/2;
    _titleLabel.centerY = 37;
    [self.naviBar addSubview:_titleLabel];
}
//查看收藏
- (IBAction)lookCollection:(id)sender {
    //判断是否已收藏
    if(![AppDelegate appDealegate].uid.length){
        LoginViewController *login = [[LoginViewController alloc]init];
        login.isModel = YES;
        BaseNavigationViewController *baseNavi = [[BaseNavigationViewController alloc]initWithRootViewController:login];
        [self presentViewController:baseNavi animated:YES completion:nil];
        return;
    }
    ColelctViewController *colectionViewCtrl = [[ColelctViewController alloc]init];
    [self.navigationController pushViewController:colectionViewCtrl animated:YES];
}

//收藏和取消收藏
- (IBAction)middle:(UIButton*)sender {
    if(![AppDelegate appDealegate].uid.length){
        LoginViewController *login = [[LoginViewController alloc]init];
        login.isModel = YES;
        BaseNavigationViewController *baseNavi = [[BaseNavigationViewController alloc]initWithRootViewController:login];
        [self presentViewController:baseNavi animated:YES completion:nil];
        return;
    }
    QickScanModel *model = self.dataSouce[self.currentIndex];
    NSString *pid = model.pid;
    NSString *url ;
    NSDictionary *paraDic;
    if(model.isCollection){//已经收藏  调用取消收藏接口
        paraDic = @{
                                  @"userId":USERID,
                                  @"productId":pid
                                  };

        url = DELETECOLLECTION;
        [self  disCollectionWithParam:paraDic url:url];
    }else{//未收藏 调用收藏接口
        paraDic = @{
                                  @"uid":USERID,
                                  @"pid":pid
    };

        url = COLLECTIONGOODS;
        [self  collectionWithParam:paraDic url:url];
    }
}

//收藏接口
-(void)collectionWithParam:(NSDictionary*)prama  url:(NSString*)url{
    [Tools AFNetworkingRequestTypePostWithUrl:url paramters:prama  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"收藏商品接口--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]])return ;
            if([dataDic[@"status"] isEqualToString:@"true"]){//收藏成功
                [MBProgressHUD showTipMessageInWindow:@"收藏成功"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.collectionButon setImage:[UIImage imageNamed:@"icon_shoucang_sel"] forState:UIControlStateNormal];
                    [self.rightButton setTitle:@"取消收藏" forState:UIControlStateNormal];
                    QickScanModel *model = self.dataSouce[self.currentIndex];
                    model.isCollection = YES;
                    self.scan.dataSoure = self.dataSouce;
                });
            }else{
                if(dataDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                }
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }

        }
    }];
}
//取消收藏接口
-(void)disCollectionWithParam:(NSDictionary*)prama  url:(NSString*)url{
    [Tools AFNetworkingRequestTypePostWithUrl:url paramters:prama  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"取消收藏商品接口--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]])return ;
            if([dataDic[@"status"] isEqualToString:@"true"]){//取消收藏成功
                [MBProgressHUD showTipMessageInWindow:@"取消收藏成功"];
                //回到主线程
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.collectionButon setImage:[UIImage imageNamed:@"icon_shoucang_nor"] forState:UIControlStateNormal];
                    [self.rightButton setTitle:@"加入收藏" forState:UIControlStateNormal];
                    QickScanModel *model = self.dataSouce[self.currentIndex];
                    model.isCollection = NO;
                    self.scan.dataSoure = self.dataSouce;
                });
            }else{
                if(dataDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                }
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
